package com.xiaolin.admin.handler;

import com.xiaolin.admin.enums.StatusCode;
import com.xiaolin.admin.exception.ServiceException;
import com.xiaolin.admin.utils.OptResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaolin
 * @description 全局异常处理器
 * @since 2023/5/11
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public OptResult handleServiceException(ServiceException e) {
        e.printStackTrace();
        return OptResult.fail(StatusCode.SERVICE_ERR, e.getMessage());
    }

    /**
     * 数据校验异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public OptResult handleBindException(BindException e) {
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> errors = fieldErrors.stream()
                .map(item -> "{ 非法参数：" + item.getField() + "，" + "出错原因：" + item.getDefaultMessage() + " }")
                .collect(Collectors.toList());
        return OptResult.fail(StatusCode.SERVICE_ERR, errors.toString());
    }

    /**
     * 数字处理异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ArithmeticException.class)
    public OptResult handleArithmeticException(ArithmeticException e) {
        e.printStackTrace();
        return OptResult.fail(StatusCode.SYS_ERR, e.getMessage());
    }


    /**
     * 系统异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public OptResult handleException(Exception e) {
        e.printStackTrace();
        return OptResult.fail(StatusCode.SYS_ERR, "系统错误，请联系管理员");
    }

}
